<!--
 * @description 平台商城-提货券
 * @author dumeng
 * @date 2021/7/28
 -->
<template>
  <div class="ptthq-page">
    <el-form ref="ptthqForm" :model="form" :rules="rules" label-width="180px">
      <el-form-item label="商户白名单" prop="dataId">
        <div class="dhq">
          <el-select
            v-model="form.dataId"
            :disabled="!!id"
            placeholder="请选择"
            style="width: 100%"
            @change="handleShChange"
          >
            <el-option
              v-for="(item, index) in merchantList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <i class="el-icon-refresh refresh-i" @click="getMallAccounts" />
          <br>
          <span v-if="!id" class="tip">
            如果没有登记线下门店信息，点击这里
            <el-button type="text" @click="shbmdVisible = true">去创建></el-button>
            商户白名单。
          </span>
        </div>

      </el-form-item>
      <el-form-item label="提货券" prop="classifType2">
        <el-tag v-if="form.classifType2" :closable="!id" @close="handleShChange()">{{ form.areaName }}</el-tag>
        <el-button v-else class="button-new-tag" size="small" @click="showCoupons">选择提货券</el-button>
      </el-form-item>
      <el-form-item label="提货券领取起止时间" prop="receiveTime">
        <el-date-picker
          v-model="form.receiveTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
          :style="{width:'100%'}"
          type="datetimerange"
          :default-time="['00:00:00', '23:59:59']"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm:ss"
          @change="syncData"
        />
      </el-form-item>
      <el-form-item label="提货券使用起止时间" prop="useTime">
        <el-date-picker
          v-model="form.useTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          clearable
          disabled
          :style="{width:'100%'}"
          type="datetimerange"
          format="yyyy-MM-dd HH:mm"
          value-format="yyyy-MM-dd HH:mm:ss"
        />
      </el-form-item>
      <el-form-item label="使用说明" prop="explain">
        <el-input
          v-model="form.explain"
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 6 }"
          placeholder="请输入使用说明"
        />
      </el-form-item>
    </el-form>
    <shbmd :visible.sync="shbmdVisible" @select="selectShbmd" />
    <el-dialog
      v-el-drag-dialog
      :destroy-on-close="true"
      :close-on-click-modal="false"
      width="800px"
      title="选择提货券"
      center
      :visible.sync="innerVisible"
      append-to-body
    >
      <el-table height="400" :data="mallCoupons">
        <el-table-column property="couponId" label="提货券模板ID" />
        <el-table-column property="couponName" label="提货券名称" />
        <el-table-column property="couponState" :formatter="getState" label="提货券状态" />
        <el-table-column label="操作" width="50">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="selectCoupon(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getMallCoupons()"
      />
    </el-dialog>
  </div>
</template>

<script>
import shbmd from '../components/shbmd'
import Pagination from '@/components/Pagination'
import elDragDialog from '@/directive/el-drag-dialog'
import { queryMerchant, merchantCoupons } from '../api/index'
export default {
  name: 'Ptthq',
  components: { shbmd, Pagination },
  directives: { elDragDialog },
  props: {
    data: {
      type: Object,
      default: () => {}
    },
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      merchantList: [],
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      mallCoupons: [],
      form: {
        dataId: '',
        classifType2: '',
        areaName: '',
        receiveTime: '',
        useTime: '',
        explain: ''
      },
      rules: {
        dataId: [{ required: true, message: '请选择商户白名单', trigger: 'change' }],
        classifType2: [{ required: true, message: '请选择提货券', trigger: 'change' }],
        receiveTime: [{ required: true, message: '请选择提货券领取起止时间', trigger: 'change' }],
        useTime: [{ required: true, message: '请选择提货券使用起止时间', trigger: 'change' }]
      },
      shbmdVisible: false,
      innerVisible: false
    }
  },
  created() {
    this.$bus.$on('refresh', this.getMallAccounts)
    this.getMallAccounts().then(() => {
      if (this.data.classifType2) {
        for (const i in this.form) {
          this.$set(this.form, i, this.data[i] || '')
        }
        this.form.receiveTime = [this.data.receiveStarttime, this.data.receiveEndtime]
        this.form.useTime = [this.data.expirationStartdate, this.data.expirationDate]
        delete this.form.receiveStarttime
        delete this.form.receiveEndtime
        delete this.form.expirationStartdate
        delete this.form.expirationDate
      }
    })
  },
  beforeDestroy() {
    this.$bus.$off('refresh', this.getMallAccounts)
  },
  methods: {
    syncData(val) {
      this.$set(this.form, 'useTime', val)
    },
    /**
     * 获取商户白名单
     */
    getMallAccounts() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        queryMerchant().then(res => {
          loading.close()
          const arr = res.data.data || []
          this.merchantList = arr.map(a => ({
            ...a,
            value: a.id,
            label: `${a.merchantName}-${a.merchantNumber}[${a.statusValue}]`
          }))
          resolve(arr)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    async showCoupons() {
      if (this.form.dataId === '') {
        this.$message.error('请选择商户白名单')
        return
      }
      this.listQuery.page = 1
      this.listQuery.pageSize = 10
      this.total = 0
      await this.getMallCoupons()
      this.innerVisible = true
    },
    getMallCoupons(obj) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        const query = {
          merchantId: this.form.dataId,
          page: obj ? obj.page : this.listQuery.page,
          pageSize: obj ? obj.limit : this.listQuery.limit
        }
        merchantCoupons(query).then(res => {
          loading.close()
          const arr = res.data.data.data || []
          this.mallCoupons = res.data.data.data || []
          this.total = res.data.data.total || 0
          resolve(arr)
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    getState(row, tag) {
      const t = row[tag]
      let text = '正常'
      switch (t) {
        case '01':
          text = '过期'
          break
        case '02':
          text = '作废'
          break
        case '03':
          text = '未生效'
          break
        case '04':
          text = '以转增'
          break
      }
      return text
    },
    selectCoupon(row) {
      this.form.classifType2 = row.couponId
      this.form.areaName = row.couponName
      this.innerVisible = false
    },
    /**
     * 切换商户白名单清空选择的提货券
     */
    handleShChange() {
      this.form.classifType2 = ''
      this.form.areaName = ''
    },
    /**
     * 从创建商户白名单弹框中选择的商户
     * @param id
     */
    selectShbmd(id) {
      // 判断已选择的商户在下拉列表数据中是否存在
      if (this.merchantList.findIndex(item => { return item.value === id }) > -1) {
        this.form.dataId = id
        this.handleShChange()
      } else {
        this.getMallAccounts().then(() => {
          this.form.dataId = id
          this.handleShChange()
        })
      }
    },
    validateForm() {
      return new Promise((resolve) => {
        this.$refs['ptthqForm'].validate((valid) => {
          if (valid) {
            const query = {
              dataId: this.form.dataId,
              areaName: this.form.areaName,
              classifType2: this.form.classifType2,
              explain: this.form.explain,
              receiveStarttime: this.form.receiveTime ? this.form.receiveTime[0] : '',
              receiveEndtime: this.form.receiveTime ? this.form.receiveTime[1] : '',
              expirationStartdate: this.form.useTime ? this.form.useTime[0] : '',
              expirationDate: this.form.useTime ? this.form.useTime[1] : ''
            }
            if (new Date(query.receiveEndtime).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券领取结束时间不得小于当前时间！',
                type: 'warning'
              })
              return
            }
            if (new Date(query.expirationDate).getTime() < new Date().getTime()) {
              this.$message({
                message: '兑换券已过期，请选择其他兑换券！',
                type: 'warning'
              })
              return
            }
            resolve(query)
          } else {
            resolve('')
          }
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tip{
  color: #666;
}
  .dhq{
  position: relative;
  .refresh-i{
    color:#ccc;
    padding-left:8px;
    cursor:pointer;
    position: absolute;
    right:-28px;
    top:5px;
    font-size: 26px;
  }
}
</style>
